<?php


namespace App\Http\Resources;


use App\Models\Favorite;
use App\Models\Member;
use App\Models\Publisher;
use Illuminate\Http\Resources\Json\JsonResource;

class TopicResource extends JsonResource
{
    public function toArray($request)
    {
        $member_id = 0;
        $is_fav = 0;

        //获取用户id
        if (auth('api')->check()) {
            $member_id = auth('api')->user()->id;
            $is_fav = Favorite::where(['member_id' => $member_id, 'topic_id' => $this->id])->count();
        }

        $data = [
            'id'             => $this->id,
            'member_id'      => $this->member_id,
            'title'          => $this->title,
            'content'        => $this->content,
            'files'          => $this->files == '' ? [] : explode(',', $this->files),
            'relay_count'    => $this->relay_count,
            'fav_count'      => $this->fav_count,
            'is_hot'         => $this->is_hot,
            'created_at'     => date("m月d日 H:i", strtotime($this->created_at)),
            'updated_at'     => date("m月d日 H:i", strtotime($this->updated_at)),
            'avatar'         => $this->member->avatar,
            'nickname'       => $this->member->nickname,
            'is_fav'         => $is_fav,
            'is_vip'         => $this->isVip($this->member_id),
            'comments_count' => $this->topic_comment_count,
            'tags'           => $this->topicTag,
            'themes'         => $this->topicTheme,
            'can_relay'      => $this->status == 1,
            'status'         => $this->status,
        ];

        return $data;
    }

    public function isVip($member_id)
    {
        $res = Member::find($member_id)->toArray();
        $openid = Publisher::where('open_id', $res['open_id'])->count();
        return $openid == 1 ? 1 : 0;
    }
}
